using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Views.ModbusCardView;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SukiUI.Dialogs;
using SukiUI.Toasts;

namespace AvaloniaApplication1.ViewModels.ModbusCardViewModel;

public partial class ModbusCardViewModel : ObservableObject
{
    /// <summary>
    /// 设备列表
    /// </summary>
    [ObservableProperty] private ObservableCollection<ModbusConfig> _modbusDeviceItems;

    /// <summary>
    /// Modbus管理器
    /// </summary>
    [ObservableProperty] private IModbusManager _modbusManager;

    /// <summary>
    ///  Modbus配置
    /// </summary>
    [ObservableProperty] private ModbusConfig _modbusConfigs;

    /// <summary>
    /// 选择监听的设备
    /// </summary>
    [ObservableProperty] private ModbusConfig? _selectedDevice=null;

    private ISukiDialogManager DialogManager { get; set; }
    private ISukiToastManager ToastManager { get; set; }

    // private AddModbusDeviceViewModel AddModbusDeviceVM { get; }


    /// <summary>
    /// 设备连接状态
    /// </summary>
    [ObservableProperty] private bool _isConnected = false;

    public ModbusCardViewModel(IModbusManager modbusManager, ISukiDialogManager dialogManager,
        ISukiToastManager toastManager)
    {
        ModbusManager = modbusManager;
        DialogManager = dialogManager;

        // AddModbusDeviceVM = addModbusDeviceVM;

        ModbusManager.ModbusDeviceAdded += OnModbusDeviceAdded;
        ModbusManager.ModbusDeviceRemoved += OnModbusDeviceRemoved;
        ModbusManager.ModbusDeviceStatusChanged += OnModbusDeviceStatusChanged;
        // // 初始化设备列表
        // ModbusDeviceItems = new ObservableCollection<ModbusConfig>();
        //
        // // 添加初始化设备
        // var initDevice=new ModbusConfig("请添加设备", DateTime.Now, ModbusConnectionType.RtuOverTcp,
        //     new SlaveInfo(), null, false, ModbusManager, DialogManager);
        // ModbusDeviceItems.Add(initDevice);
        
        
        var result = ModbusManager.GetAllModbusDevices();
        if (result.IsCompleted)
        {
             ModbusDeviceItems = new ObservableCollection<ModbusConfig>(result.Result);
            // foreach (var device in result.Result)
            // {
            //     ModbusDeviceItems.Add(device);
            // }
            SelectedDevice = ModbusDeviceItems.FirstOrDefault();
        }
    }

    /// <summary>
    /// 状态发生变化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void OnModbusDeviceStatusChanged(object? sender, ModbusDeviceStatusEventArgs e)
    {
        // 更新UI中的设备列表中设备的参数
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            var itemToUpdate = ModbusDeviceItems.FirstOrDefault(item => item.DeviceName == e.DeviceName);
            if (itemToUpdate != null)
            {
                itemToUpdate.IsConnected = e.IsConnected;
            }
        });
    }

    private void OnModbusDeviceRemoved(object? sender, ModbusDeviceEventArgs e)
    {
        // 移除设备后，更新UI
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            var itemToRemove = ModbusDeviceItems.FirstOrDefault(item => item.DeviceName == e.ModbusConfig.DeviceName);
            if (itemToRemove != null)
            {
                ModbusDeviceItems.Remove(itemToRemove);
            }
        });
    }

    private void OnModbusDeviceAdded(object sender, ModbusDeviceEventArgs e)
    {
        // 添加设备成功后，更新UI
        Dispatcher.UIThread.InvokeAsync(() => { ModbusDeviceItems.Add(e.ModbusConfig); });
    }

    [RelayCommand]
    public void SelectDevice(ModbusConfig modbusConfig)
    {
        if (!ModbusDeviceItems.Contains(modbusConfig))
        {
            DialogManager.CreateDialog().WithContent("设备不存在").WithActionButton("关闭", _ => { }, true)
                .TryShow();
        }

        SelectedDevice = modbusConfig;
    
      
    }


    
    /// <summary>
    /// 数据点配置
    /// </summary>
    [RelayCommand]
    public void DataPointsConfigCommand()
    {
        if (SelectedDevice == null)
        {
            DialogManager.CreateDialog()
                .WithContent("请先选择一个设备")
                .WithActionButton("确定", _ => { DialogManager.DismissDialog(); })
                .TryShow();
            return;
        }

        try
        {
            var updateDataPoints = new UpdateSlaveDataPointView
            {
                DataContext = new UpdateSlaveDataPointViewModel(SelectedDevice.DeviceName,SelectedDevice.SlaveInfo)
            };
            DialogManager.CreateDialog().WithContent(updateDataPoints)
                .WithActionButton("取消", _ => { DialogManager.DismissDialog(); }).TryShow();
        }
        catch (Exception ex)
        {
            DialogManager.CreateDialog()
                .WithContent($"数据点配置失败: {ex.Message}")
                .WithActionButton("确定", _ => { })
                .TryShow();
        }
    }

    /// <summary>
    /// 切换连接状态
    /// </summary>
    /// <param name="deviceName"></param>
    [RelayCommand]
    public void ToggleDeviceConnectionCommand(string deviceName)
    {
    }

    [RelayCommand]
    public void ToAddModbusDeviceView()
    {
        //添加设备(每次添加设备时，先清空数据)
        var addModbusDeviceVm = new AddModbusDeviceViewModel(ModbusConfigs, ModbusManager, DialogManager);

        var addView = new AddModbusDeviceView
        {
            DataContext = addModbusDeviceVm
        };
        DialogManager.CreateDialog().WithContent(addView)
            .WithActionButton("取消", _ => { DialogManager.DismissDialog(); }).TryShow();
    }
}